import * as vscode from 'vscode';
import { MCPConfig } from './mcpConfig';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import type { Tool } from '@anthropic-ai/sdk/resources/messages/messages.mjs';

export class MCPClient {
    public toolToClientMap: Map<string, Client> = new Map();

    constructor() {
    }

    public async getResult(toolCallsData: any) {
        console.log('调用的工具为:', toolCallsData);
        
        // 定义结果数组类型
        let result: Array<{
            role: string;
            tool_call_id?: string;
            name?: string;
            content: string;
        }> = [];
        
        for (const toolCall of toolCallsData) {
            const toolName = toolCall.function.name;
            const toolArguments = JSON.parse(toolCall.function.arguments);
            const toolClient = this.toolToClientMap.get(toolName);
            if (toolClient) {
                const toolResult = await toolClient.callTool({
                    name: toolName,
                    arguments: toolArguments,
                });
            
                result.push({
                    role: "tool",
                    tool_call_id: toolCall.id,
                    content: (toolResult.content as any)[0].text as string
                });
            }
        }
        
        return result;
    }


    /**
     * 连接到MCP服务器并获取工具列表
     * @param mcpConfig MCP配置对象
     */
    public async connectToMcpServer(mcpConfig: MCPConfig): Promise<Tool[]>{
        try {
            // 检查是否有可用的MCP服务器配置
            const servers = mcpConfig.mcpServers;
            if (!servers || Object.keys(servers).length === 0) {
                console.log('未找到MCP服务器配置');
                return [];
            }
            let tools: Tool[] = [];
            
            // 遍历所有配置的服务器
            for (const serverName in servers) {
                const mcp:Client = new Client({ name: serverName, version: "1.0.0" });
                const serverConfig = servers[serverName];
                // 连接到服务器并获取工具列表
                const transport = new StdioClientTransport({
                    command: serverConfig.command,
                    args: serverConfig.args,
                });
                await mcp.connect(transport);
                
                // Register tools
                const toolsResult = await mcp.listTools();
                toolsResult.tools.map((tool) => {
                    this.toolToClientMap.set(tool.name, mcp);
                    tools.push({
                        name: tool.name,
                        description: tool.description,
                        input_schema: {
                        ...tool.inputSchema,
                        type: tool.inputSchema.type || "object"
                        },
                    });
                });
            }
            return tools;
        } catch (error) {
            console.error('处理MCP服务器连接失败:', error);
            vscode.window.showErrorMessage(`连接MCP服务器失败: ${error}`);
        }
        return [];
    }

    

    

    

    
}
